package dynamic.jdk.theory;

import java.io.*;

public class MyClassLoader extends ClassLoader{
    @Override
    protected Class<?> findClass(String name) throws ClassNotFoundException {
        String prefix = MyProxy.class.getResource("").getPath();
        File base = new File(prefix);
        File f = new File(base,"$Proxy.class");
        FileInputStream fileInputStream = null;
        ByteArrayOutputStream outputStream = null;
        try {
            byte[] bytes = new byte[1024];
            fileInputStream = new FileInputStream(f);
            outputStream = new ByteArrayOutputStream();
            int len;
            while ((len = fileInputStream.read(bytes)) != -1){
                outputStream.write(bytes,0,len);
            }
            return this.defineClass(name,outputStream.toByteArray(),0,outputStream.size());
        } catch (Exception e) {
            e.printStackTrace();
        }finally {
            if (fileInputStream !=null){
                try {
                    fileInputStream.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            if (outputStream != null){
                try {
                    outputStream.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            f.delete();
        }
        return null;
    }
}
